/* eslint-disable */
<template>
  <div class="todo-app">
    <!-- 添加图标和标题动画 -->
    <div class="title-container">
      <el-icon class="title-icon"><Calendar /></el-icon>
      <h1>待办事项清单</h1>
    </div>

    <!-- 输入框和添加按钮部分改造 -->
    <div class="input-section">
      <el-input v-model="newTodo" class="input-task" placeholder="输入新的待办事项">
        <template #prefix>
          <el-icon><Edit /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="addTodo">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
    </div>

    <!-- 控制按钮样式优化 -->
    <div class="control-buttons">
      <el-button
        type="primary"
        :disabled="
          selectedSortNum === null ||
          sortedTodos.findIndex((i) => i.sortNum === selectedSortNum) === 0
        "
        @click="moveUp"
      >
        <el-icon><ArrowUp /></el-icon>
        上移
      </el-button>
      <el-button
        type="primary"
        :disabled="
          selectedSortNum === null ||
          sortedTodos.findIndex((i) => i.sortNum === selectedSortNum) === sortedTodos.length - 1
        "
        @click="moveDown"
      >
        <el-icon><ArrowDown /></el-icon>
        下移
      </el-button>
    </div>

    <!-- 筛选部分样式优化 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form :model="form.input" label-width="auto">
            <el-form-item label="内容筛选">
              <el-input v-model="form.input" placeholder="输入内容筛选" clearable>
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="10">
          <el-form-item label="状态筛选">
            <el-select v-model="form.state" placeholder="选择完成状态">
              <el-option
                v-for="i in statusConfig"
                :key="i.value"
                :label="i.text"
                :value="i.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button type="info" @click="clearTheOptions">
            <el-icon><Delete /></el-icon>
            清空筛选
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格部分样式优化 -->
    <el-table
      :data="filterTodos"
      :row-class-name="rowClassName"
      class="todo-table"
      @row-click="selectRow"
    >
      <el-table-column label="内容" prop="text" width="180" />
      <el-table-column label="排序号" prop="sortNum" width="100" />

      <el-table-column label="状态" prop="state">
        <template #default="{ row }">
          {{ statusConfig.find((i) => i.value === row.state) }}
          <el-tag
            :type="statusConfig.find((i) => Number(i.value) === row.state)?.color || 'info'"
            >{{
              statusConfig.find((i) => Number(i.value) === row.state)?.text || '未知状态'
            }}</el-tag
          >
        </template>
      </el-table-column>
      <!-- 其他列保持不变 -->
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button-group>
            <el-popconfirm
              cancel-button-text="取消"
              confirm-button-text="确定"
              title="确定要删除吗?"
              @confirm="deleteTodo(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              cancel-button-text="取消"
              confirm-button-text="确定"
              title="确定要完成吗?"
              @confirm=""
            >
              <template #reference>
                <el-button type="success" size="small">
                  <el-icon><Check /></el-icon>
                </el-button>
              </template>
            </el-popconfirm>

            <el-button type="primary" size="small">
              <el-icon><Edit /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// 添加图标导入
import {
  Calendar,
  Edit,
  Plus,
  ArrowUp,
  ArrowDown,
  Search,
  Delete,
  Check,
} from '@element-plus/icons-vue'

import { addTodo, deleteTodo, getStatusconfig, getTodos, updateTodoSortNum } from '@/api'

export default {
  components: {
    Calendar,
    Edit,
    Plus,
    ArrowUp,
    ArrowDown,
    Search,
    Delete,
    Check,
  },
  data() {
    return {
      newTodo: '',
      selectedSortNum: null, // 用于记录选中行的排序号
      todos: [], //存放数据库表数据
      statusConfig: [],
      //保存筛选条件
      form: {
        input: '',
        state: null,
      },
    }
  },

  async created() {
    await this.fetchTodos()
  },
  computed: {
    // 根据 初始化时候 根据数据库的 sortNum 排序后的 todos 列表
    sortedTodos() {
      return this.todos.slice().sort((a, b) => a.sortNum - b.sortNum)
    },
    filterTodos() {
      return this.sortedTodos.filter((item) => {
        // 内容过滤: 如果 form.input 有值，则返回包含该值的待办事项
        //内容过滤,留下 form.input === item.input的
        const matchesInput = !this.form.input || item.text.includes(this.form.input)

        // 状态过滤: 如果 form.state 有值，则返回与状态匹配的待办事项
        //状态过滤,留下form.state === item.state的
        const matchesState = this.form.state === null || item.state === Number(this.form.state)

        // 同时满足内容和状态过滤条件
        return matchesInput && matchesState
      })
    },
  },
  methods: {
    clearTheOptions() {
      this.form.input = ''
      this.form.state = null
    },
    //刷新表格数据
    async fetchTodos() {
      try {
        const res = await getTodos()
        this.todos = res.data
        console.log(this.todos)
      } catch (error) {
        this.$message.error('加载待办事项失败，请稍后重试。')
      }
      try {
        const res = await getStatusconfig()
        this.statusConfig = res.data
      } catch (e) {
        console.error('Error loading statusConfig:', error)
      }
    },
    //添加新的todolist
    async addTodo() {
      if (!this.newTodo.trim()) {
        this.$message({
          message: '请输入内容!',
          type: 'warning',
        })
        return
      }
      // 获取当前最大排序号，并加一
      const maxSortNum =
        this.todos.length > 0 ? Math.max(...this.todos.map((todo) => todo.sortNum)) : 0
      try {
        const res = await addTodo({
          text: this.newTodo,
          sortNum: maxSortNum + 1,
        })
        await this.fetchTodos()
      } catch (error) {
        this.$message({
          message: '添加失败',
          type: 'warning',
        })
      }
      this.newTodo = ''
    },
    //根据id删除todolist
    async deleteTodo(id) {
      try {
        const res = await deleteTodo(id)
        console.log(res.status)
        if (res.status === 200)
          this.$message({
            message: '删除成功!',
            type: 'success',
          })
        await this.fetchTodos()
      } catch (e) {
        this.$message({
          message: '删除失败',
          type: 'warning',
        })
      }
    },

    // 上移
    async moveUp() {
      const currentIndex = this.sortedTodos.findIndex(
        (todo) => todo.sortNum === this.selectedSortNum
      )
      if (currentIndex > 0) {
        const currentTodo = this.sortedTodos[currentIndex]
        const previousTodo = this.sortedTodos[currentIndex - 1]
        this.selectedSortNum = previousTodo.sortNum // 更新选中的排序号
        await this.swapSortNums(currentTodo, previousTodo)
      }
    },

    // 下移
    async moveDown() {
      const currentIndex = this.sortedTodos.findIndex(
        (todo) => todo.sortNum === this.selectedSortNum
      )
      if (currentIndex < this.sortedTodos.length - 1) {
        const currentTodo = this.sortedTodos[currentIndex]
        const nextTodo = this.sortedTodos[currentIndex + 1]
        this.selectedSortNum = nextTodo.sortNum // 更新选中的排序号
        await this.swapSortNums(currentTodo, nextTodo)
      }
    },

    // 交换两个任务的排序号并更新数据库
    async swapSortNums(todo1, todo2) {
      // 交换排序号
      const tempSortNum = todo1.sortNum
      todo1.sortNum = todo2.sortNum
      todo2.sortNum = tempSortNum

      try {
        // 更新数据库中的排序号
        await updateTodoSortNum(todo1.id, todo1.sortNum)
        await updateTodoSortNum(todo2.id, todo2.sortNum)
      } catch (error) {
        console.error('Error updating sort order:', error)
        this.$message({
          message: '更新排序失败，请重试',
          type: 'warning',
        })
      }
    },

    selectRow(row) {
      this.selectedSortNum = row.sortNum
    },
    rowClassName({ row }) {
      //知道selectedSortNum,让{ "id": 7, "text": "Learn Vue basics", "sortNum": 1 }里面的sortNum等于知道selectedSortNum的时候变色
      return row.sortNum === this.selectedSortNum ? 'selected-row' : ''
    },
  },
}
</script>

<style>
.todo-app {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background: linear-gradient(145deg, #ffffff, #f0f2f5);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.title-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  margin-bottom: 2rem;
  animation: fadeIn 0.5s ease-in-out;
}

.title-icon {
  font-size: 2rem;
  color: var(--el-color-primary);
}

h1 {
  color: var(--el-text-color-primary);
  font-size: 2rem;
  margin: 0;
}

.input-section {
  margin-bottom: 2rem;
  display: flex;
  gap: 1rem;
}

.input-task {
  transition: all 0.3s ease;
}

.input-task:focus-within {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.control-buttons {
  margin-bottom: 2rem;
}

.filter-section {
  background-color: var(--el-bg-color-page);
  padding: 1.5rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.todo-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.selected-row {
  background-color: var(--el-color-primary-light-9) !important;
  transition: background-color 0.3s ease;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 添加动画关键帧 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 添加过渡效果 */
.el-table-column {
  transition: all 0.3s ease;
}

.el-tag {
  transition: all 0.3s ease;
}

.el-button-group {
  display: flex;
  gap: 4px;
}
</style>
